import router from '@/router/index.js'
import store from '@/store/index.js'
// import { asyncRoutes, constantRoutes } from '@/router/index'

// 全局前置路由守卫
router.beforeEach(async function(to, from, next) {
  if (['/login', '/404', '/learn-vuex'].includes(to.path)) return next()
  // 判断是否登录
  if (store.state.user.token) {
    // 判断用户信息为空
    if (!store.state.user.userinfo.userId) {
      await store.dispatch('user/getUserInfos')
      // const menus = store.state.user.userinfo.roles.menus
      // 过滤菜单
      // const filterRoutes = asyncRoutes.filter(item => {
      //   return menus.includes(item.children[0].name)
      // })
      // // 添加路由配置离去
      // // 注意动态加路由，没有影响最开始的配置
      // router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
      // router.options.routes = [...constantRoutes, ...filterRoutes]

      // 拿到需要匹配权限的路由
      const menus = store.state.user.userinfo.roles.menus
      // 进行动态路由筛选
      const filterRoutes = await store.dispatch('permission/fiterRoutes', menus)
      // 添加动态路由
      router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
      console.log(router, 'router')
      // 更改初始路由配置
      // router.options.routes = [...constantRoutes, ...filterRoutes]
      return next(to.path)
    }

    next()
  } else {
    next('/login')
  }
})
// 全局后置路由守卫
router.afterEach(function(to, from) {

})
